package com.xxx.dorm.web.filter;

import com.xxx.dorm.domain.Users;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"/dormBuild/*","/user/findAll","/user/changePassword","/user/mainIndex","/user/findOldPassword","/user/findOneUser","/user/addUser","/user/deleteUser","/user/updateUser"})
public class permissionsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        Users users = (Users) request.getSession().getAttribute("user");
        if(uri.equals("/user/mainIndex")){
            request.setAttribute("error","");
            filterChain.doFilter(request, response);
        } else if(users.getRid()==1){
            filterChain.doFilter(request, response);
        } else {
            request.setAttribute("error","你没有权限！");
            request.getRequestDispatcher("/user/mainIndex").forward(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
